//
//  NSObject+Model.m
//  runtime字典转模型
//
//  Created by 李松 on 2017/11/23.
//  Copyright © 2017年 李松. All rights reserved.
//

#import "NSObject+Model.h"
#import <objc/message.h>

@implementation NSObject (Model)

+ (instancetype)modelWithDic:(NSDictionary *)dic{
    
    //runtime:遍历模型中所有成员属性, 去字典中查找
    //属性定义在类中, 类中可以拿到属性列表
    
    id obj = [[self alloc] init];
    
    unsigned int count = 0;
    Ivar *ivarList = class_copyIvarList(self, &count);
    
    //NSLog(@"%d", count);
    for (int i = 0; i < count; i++) {
        
        Ivar ivar = ivarList[i];
        //NSLog(@"%s", ivar_getName(ivar));
        //成员属性名
        NSString *propertyName = [NSString stringWithUTF8String:ivar_getName(ivar)];
        //成员属性类型
        NSString *propertyType = [NSString stringWithUTF8String:ivar_getTypeEncoding(ivar)];
        
        //获取key
        NSString *key = [propertyName substringFromIndex:1];
        //获取字典的value
        id value = [dic objectForKey:key];
        
        //二级转换, 值是字典, 成员属性不是字典, 才能转换成模型
        if ([value isKindOfClass:[NSDictionary class]] && ![propertyType containsString:@"NS"]) {
            //注意: propertyType 实际是 @"@\"FriendItem\""
            //NSLog(@"%@", propertyType);
            NSRange range = [propertyType rangeOfString:@"\""];
            propertyType = [propertyType substringFromIndex:range.location + range.length];
            range = [propertyType rangeOfString:@"\""];
            propertyType = [propertyType substringToIndex:range.location];;
            
            Class modelClass = NSClassFromString(propertyType);
            //NSLog(@"%@", modelClass);
            if (modelClass) {
                value = [modelClass modelWithDic:value];
            }
        }
        
        if (value) {
            [obj setValue:value forKey:key];
        }
        //NSLog(@"%@ %@", propertyName, propertyType);
    }
    return obj;
}

@end
